<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2024/4/23
 * Time: 15:19
 */

namespace app\logic\index\oversea;


use app\common\lib\Common;
use app\common\lib\Guzzle;
use app\exception\IndexException;
use app\logic\BaseLogic;
use app\model\novel\NovelChapterModel;
use app\model\novel\NovelSpreadModel;
use app\model\plan\PromotionPlanOverseaModel;
use support\Db;

class OverseaLogic extends BaseLogic
{
    protected $model;

    protected static $instance;

    public function __construct()
    {
        parent::__construct();
        $this->model = \app\model\user\UserPromotionOverseaModel::getInstance();
    }

    public static function getInstance()
    {
//        if(is_object(self::$instance)){
//            return self::$instance;
//        }

        return  new self();
    }

    public function submitData($param)
    {
        if(Common::setnx('oversea_submitData_'.request()->curUserId)==false){
            throw new IndexException(4020,'请求频繁');
        }

        if(mb_strlen($param['content'])<300 || mb_strlen($param['content'])>18000 ){
            throw new IndexException(4020,'内容字数要在300-18000之间');
        }
        if(preg_match('/[\x{4e00}-\x{9fa5}]+/u',$param['content'])){
            throw new IndexException(4020,'内容不能出现中文');
        }

        $contentArr = str_replace([',','.','?','!'], "\n",$param['content']);
        $contentArrs = array_values(array_filter(explode("\n",$contentArr)));

        $contentStr = [];
        $parts = [];
        /*2024-09-18迭代*/
        if (in_array($param['style_type'], [3, 4]) ) {
            $parts = $param['chat_messages'];
        } else {
            foreach($contentArrs as $n=>$con){
                $contentStr[] = $contentArrs[$n];
                if(strlen(implode(',',$contentStr))>990){
                    array_pop($contentStr);
                    $parts[] = implode(',',$contentStr);
                    $contentStr = [$contentArrs[$n]];
                }

                //加上最后一个
                if(count($contentArrs)==($n+1)){
                    $parts[] = implode(',',$contentStr);
                }
            }
        }

        $subTitles = [];
        foreach ($parts as $k=>$part){
            //内容必须包含字母或数字，不能只有符号
            if(preg_match('/[a-z|A-Z|0-9]+/',$part)==false){
                unset($parts[$k]);
                continue;
            }

            $content = str_replace([','], "\n",$part);
            $contents = array_values(array_filter(explode("\n",$content)));
            $subTitles[] = $contents;
        }
        $parts = array_values($parts);

        //去重设置
        $settings = !empty($param['settings']) ? json_decode($param['settings'],true) : [];
        $settingsKeys = ['random_reduce','random_add','random_speed','random_mirror','random_hash','random_filter','random_effect','random_transition','random_enlarge'];
        foreach ($settingsKeys as $val){
            $settings[$val] = (int)(isset($settings[$val])?$settings[$val]:1);
        }

        //素材选择
        $videoRate = $param['video_rate']??'9:16';
        $materialDatas = [];
        if(!empty($param['material_id'])){
            $materialData = getMaterialData($param['material_id']);
            if ($materialData) {
                //分辨率要一致
//                $heigh = [];
//                foreach($materialData['heigh'] as $video){
//                    if($video['video_scale']==$videoRate){
//                        $heigh[] = $video;
//                    }
//                }
//                $normal = [];
//                foreach($materialData['normal'] as $video){
//                    if($video['video_scale']==$videoRate){
//                        $normal[] = $video;
//                    }
//                }

//                $heigh = [];
//                foreach ($materialData['heigh'] as $video) {
//                    if ($video['height']<= 1920 && $video['height']>=1080 && $video['width']<=1920 &&$video['width']>=1080) {
//                        $heigh[] = $video;
//                    }
//                }
//                $normal = [];
//                foreach ($materialData['normal'] as $video) {
//                    if ($video['height']<= 1920 && $video['height']>=1080 && $video['width']<=1920 &&$video['width']>=1080) {
//                        $normal[] = $video;
//                    }
//                }

                //目前不考虑分辨率
                $heigh = $materialData['heigh'];
                $normal = $materialData['normal'];

                //打乱素材视频顺序
                $heigh && shuffle($heigh);
                $normal && shuffle($normal);
                $materialDatas = ['heigh'=>$heigh,'normal'=>$normal];
            }
        }
        $localVideo = !empty($param['local_video']) ? json_decode($param['local_video'],true):'';
        if(empty($localVideo) && empty($materialDatas['heigh']) &&  empty($materialDatas['normal'])){
            throw new IndexException(4020, '视频素材不能为空');
        }

        //2024-09-18版本迭代
        /*聊天框的图片数组*/
        if (!empty($param['chat_images'])) {
            $param['chat_images'] = array_filter($param['chat_images'], function ($url) {
                return filter_var($url, FILTER_VALIDATE_URL);
            });
            $param['chat_images'] = array_values($param['chat_images']);
        }
        /*卡片图片地址*/
        $param['card_image'] = !empty($param['card_image']) && filter_var($param['card_image'], FILTER_VALIDATE_URL) ? $param['card_image'] : '';

        if (!empty($param['chat_messages'])) {
            foreach ($param['chat_messages'] as &$messages) {
                $messages = htmlspecialchars(trim($messages));
            }
        }


        $insert = [
            'user_sn'=>request()->curUserId,
            'content'=>$param['content'],
            'musicid'=>$param['musicid']??0,
            'timbreid'=>$param['timbreid']??0,
            'music_volume'=>!empty($param['music_volume'])?$param['music_volume']:10,
            'timbre_volume'=>!empty($param['timbre_volume'])?$param['timbre_volume']:10,
            'speak_speed'=>!empty($param['speak_speed'])?$param['speak_speed']:10,
            'fontid'=>$param['fontid']??0,
            'video_rate'=>$videoRate,
            'part_content'=>json_encode(array_values($parts),256),
            'subtitle'=>json_encode($subTitles,256),

            'material_id'=>$param['material_id']??'',
            'material_data'=>$materialDatas ? json_encode($materialDatas,256) : '',
            'local_video'=>!empty($localVideo) ? json_encode($localVideo,256):'',
            'settings'=>json_encode($settings),
            'font_size'=>!empty($param['font_size'])?$param['font_size']:0,
            'caption_post_x'=>!empty($param['caption_post_x'])?$param['caption_post_x']:0,
            'caption_post_y'=>!empty($param['caption_post_y'])?$param['caption_post_y']:0,
            'type'=>1,

            /*2024-09-18版本迭代*/
            'style_type'=>!empty($param['style_type']) ? intval($param['style_type']) : 0 ,/*风格列表中的type*/
            'chat_images'=>!empty($param['chat_images']) ? json_encode($param['chat_images']) : '' ,/*聊天框的图片数组*/
            'chat_messages'=>!empty($param['chat_messages']) ? json_encode($param['chat_messages']) : '' ,/*内容图片数组*/
            'card_image'=>!empty($param['card_image']) ? trim($param['card_image']) : '' ,/*卡片图片地址*/
            'card_remain'=>!empty($param['card_remain']) ? intval($param['card_remain']) : 0 ,/*卡片停留时长(秒)*/
            'card_top'=>!empty($param['card_top']) ? intval($param['card_top']) : 0 ,
            'card_content'=>!empty($param['card_content']) ? trim($param['card_content']) : '' ,
        ];
        $id = $this->model->insertGetId($insert);

        //todo 1 所需扣除用户点数
        $strLen = 0;
        foreach ($parts as $part){
            $strLen += strlen($part);
        }
        $totalPonint = round(ceil($strLen/3000)*10);

        return ['id'=>$id,'total_point'=>$totalPonint];
    }

    public function submitDataByOverseaNovel($param)
    {
        $novel = NovelSpreadModel::getInstance()->getWhere(['novel_sn'=>$param['novel_sn'],'spread_type'=>3])->first();
        if($novel==false){
            throw new IndexException(4020,'推文不存在');
        }
        $where = ['novel_sn'=>$param['novel_sn'],['original_content','<>','']];
        $chapter = NovelChapterModel::getInstance()->getWhere($where)->orderBy(Db::Raw('RAND()'))->first();
        if($chapter==false){
            throw new IndexException(4020,'推文内容不存在');
        }
        //随机获取当前海外方案
        $plan = false;
        if(!empty($param['id'])){
            $plan = PromotionPlanOverseaModel::getInstance()->find($param['id']);
        }
        if($plan==false){
            $where = ['isdel' => 0, 'status' => 1, 'lang' => $novel['lang']];
            $plan = PromotionPlanOverseaModel::getInstance()->getWhere($where)->orderBy(Db::Raw('RAND()'))->first();
            if($plan==false){
                throw new IndexException(4020,'没有符合方案');
            }
        }

        if(empty($chapter['content'])){
            if(empty($chapter['original_content'])){
                throw new IndexException(4020,'推文内容不能为空');
            }
            if(preg_match('/[\x{4e00}-\x{9fa5}]+/u',$chapter['original_content'])){
                throw new IndexException(4020,'推文内容不能出现中文');
            }

            $cmd = getAiCommand('original_content_ai_command_overseas');
            if(empty($cmd)){
                throw new IndexException(4020,'指令不能为空');
            }

            $replaceStr =  ["\r",'`','~','@','#','$','^','&','*','(',')','=','|','{','}','\\','[',']','<','>',
                            '《','》','/','￥','……','（','）','――','【','】','‘','”', '“','"','\'',' ','「','」'];
            $contentText = str_replace($replaceStr,"",$chapter['original_content']);

            $content = Common::generatedContent($contentText,$cmd,$novel['lang']);
            if(strlen($content)>200){
                NovelChapterModel::getInstance()->getWhere(['id'=>$chapter['id']])->update(['content'=>$content]);
            }else{
                throw new IndexException(4020,'推文内容错误');
            }
        }else{
            $content = $chapter['content'];
        }

        $parts = array_values(array_filter(explode("\n",$content)));
        $subTitles = [];
        foreach ($parts as $k=>$part){
            //内容必须包含字母或数字，不能只有符号
            if(preg_match('/[a-z|A-Z|0-9]+/',$part)==false){
                unset($parts[$k]);
                continue;
            }
            $content = str_replace([','], "\n",$part);
            $contents = array_values(array_filter(explode("\n",$content)));
            $subTitles[] = $contents;
        }
        $parts = array_values($parts);

        //去重设置
        $settings = !empty($plan['settings']) ? json_decode($plan['settings'], true) : [];
        $settingsKeys = ['random_reduce','random_add','random_speed','random_mirror','random_hash','random_filter','random_effect','random_transition','random_enlarge'];
        foreach ($settingsKeys as $val){
            $settings[$val] = (int)(isset($settings[$val])?$settings[$val]:1);
        }

        //素材选择
        $videoRate = $plan['video_scale']??'9:16';
        $materialDatas = [];
        if(!empty($plan['material_id'])){
            $materialData = getMaterialData($plan['material_id']);
            if ($materialData) {
                //分辨率要一致
//                $heigh = [];
//                foreach ($materialData['heigh'] as $video) {
//                    if ($video['video_scale'] == $videoRate) {
//                        $heigh[] = $video;
//                    }
//                }
//                $normal = [];
//                foreach ($materialData['normal'] as $video) {
//                    if ($video['video_scale'] == $videoRate) {
//                        $normal[] = $video;
//                    }
//                }

//                $heigh = [];
//                foreach ($materialData['heigh'] as $video) {
//                    if ($video['height']<= 1920 && $video['height']>=1080 && $video['width']<=1920 &&$video['width']>=1080) {
//                        $heigh[] = $video;
//                    }
//                }
//                $normal = [];
//                foreach ($materialData['normal'] as $video) {
//                    if ($video['height']<= 1920 && $video['height']>=1080 && $video['width']<=1920 &&$video['width']>=1080) {
//                        $normal[] = $video;
//                    }
//                }

                //目前不考虑分辨率
                $heigh = $materialData['heigh'];
                $normal = $materialData['normal'];

                //打乱素材视频顺序
                $heigh && shuffle($heigh);
                $normal && shuffle($normal);
                $materialDatas = ['heigh'=>array_slice($heigh,0,50),'normal'=>array_slice($normal,0,100)];
            }
        }
        if(empty($materialDatas['heigh']) &&  empty($materialDatas['normal'])){
            throw new IndexException(4020, '视频素材不能为空');
        }

        $insert = [
            'user_sn'=>request()->curUserId,
            'novel_sn'=>$chapter['novel_sn'],
            'chapterid'=>$chapter['id'],
            'content'=>$content,
            'planid'=>$plan['id'],
            'musicid'=>$plan['musicid']??0,
            'timbreid'=>$plan['timbreid']??0,
            'music_volume'=>!empty($plan['music_volume'])?$plan['music_volume']:10,
            'timbre_volume'=>!empty($plan['timbre_volume'])?$plan['timbre_volume']:10,
            'speak_speed'=>!empty($plan['speak_speed'])?$plan['speak_speed']:10,
            'fontid'=>$plan['fontid']??0,
            'video_rate'=>$videoRate,
            'part_content'=>json_encode(array_values($parts),256),
            'subtitle'=>json_encode($subTitles,256),

            'material_id'=>$plan['material_id']??'',
            'material_data'=>$materialDatas ? json_encode($materialDatas,256) : '',
            'settings'=>json_encode($settings),
            'font_size'=>$plan['font_size']??10,
            'caption_post_x'=>!empty($plan['caption_post_x'])?$plan['caption_post_x']:0,
            'caption_post_y'=>!empty($plan['caption_post_y'])?$plan['caption_post_y']:0,
            'type'=>2,
        ];
        $id = $this->model->insertGetId($insert);

        //todo 1 所需扣除用户点数
        $strLen = 0;
        foreach ($parts as $part){
            $strLen += strlen($part);
        }
        $totalPonint = round(ceil($strLen/3000)*10);

        return ['id'=>$id,'total_point'=>$totalPonint];
    }

    public function getPlanList($param)
    {
        $where = [
            'status'=>1,
            'isdel'=>0
        ];
        if(!empty($param['lang'])){
            $where['lang'] = $param['lang'];
        }else{
            $where['lang'] = 'en';
        }
        $order = ['id','desc'];
        $field = ['id','name','image','lang'];
        $data = PromotionPlanOverseaModel::getInstance()->index($where,$field,$order);

        return $data;
    }
}